package com.robinmouren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.robinmouren.constant.MessageConstant;
import com.robinmouren.constant.StatusConstant;
import com.robinmouren.dto.QuotationDto;
import com.robinmouren.dto.SplitGoodsDto;
import com.robinmouren.entity.*;
import com.robinmouren.exception.NullInfoException;
import com.robinmouren.exception.NullOrderInfoException;
import com.robinmouren.mapper.SplitGoodsMapper;
import com.robinmouren.service.ISplitGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 货物拆分表 服务实现类
 * </p>
 *
 * @author Robinmouren
 * @since 2024-05-23
 */
@Service
public class SplitGoodsServiceImpl extends ServiceImpl<SplitGoodsMapper, SplitGoods> implements ISplitGoodsService {

    @Autowired
    private OrderInfoServiceImpl orderInfoService;
    @Autowired
    private OrderDetailServiceImpl orderDetailService;


    /**
     * 保存拆分后的货物信息
     * @param dto
     */
    @Override
    public void saveGoods(SplitGoodsDto dto) {

        String orderNumber = dto.getOrderNumber();
        QuotationDto dtoData = dto.getData();
        List<SplitGoodsList> goods = dto.getGoods();

        // 获取订单信息
        OrderInfo orderinfo = orderInfoService.getOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getOrderNumber, orderNumber));
        if(orderinfo == null){
            throw new NullOrderInfoException(MessageConstant.ORDER_IS_NULL);
        }
        Long id = orderinfo.getId();

        // 判断是否存在已拆分的数据，若存在则先将数据删除
        List<SplitGoods> ifExistList = this.list(new LambdaQueryWrapper<SplitGoods>()
                .eq(SplitGoods::getOrderId, id));
        if(ifExistList.size() > 0){
            this.removeBatchByIds(ifExistList);
            // 查询货物细明表中是否有信息，若有则删除
            List<OrderDetail> list = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getOrderId, id));
            if(list.size() > 0){
                orderDetailService.removeBatchByIds(list);
            }
        }


        // 如果拆分的列表长度为1，则相当于未拆分，即直接用原订单号添加
        if(goods.size() == 1){
            SplitGoods build = SplitGoods.builder()
                    .orderId(id)
                    .trackingNumber(orderNumber)
                    .build();
            this.save(build);
        }else {
            // 若否，则首先判断输入的信息是否符合要求
            // TODO 判断输入的信息是否符合要求

            goods.forEach(item -> {
                String trackingNumber = item.getTrackingNumber();
                // 分别获得运单号，并存入数据库
                SplitGoods build = SplitGoods.builder()
                        .orderId(id)
                        .trackingNumber(trackingNumber)
                        .build();
                this.save(build);
                // 获取拆分后的订单细明
                List<LoadInformation> loadInformation = item.getLoadInformation();
                List<OrderDetail> detailList = loadInformation.stream().map(obj -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(obj, orderDetail);
                    orderDetail.setOrderId(id);
                    orderDetail.setTrackingNumber(trackingNumber);
                    return orderDetail;
                }).collect(Collectors.toList());

                orderDetailService.saveBatch(detailList);
            });

        }

        // 修改订单状态
        orderinfo.setStatus(StatusConstant.SPLIT_GOODS);
        orderInfoService.updateById(orderinfo);
    }


    /**
     * 根据订单号获取拆分的货物信息
     * @param orderNumber
     * @return
     */
    @Override
    public List<SplitGoodsList> getByNum(String orderNumber) {
        // 获取订单id
        OrderInfo orderinfo = orderInfoService.getOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getOrderNumber, orderNumber));
        Long id = orderinfo.getId();

        // 获取拆分后的货物信息
        List<SplitGoods> list = this.list(new LambdaQueryWrapper<SplitGoods>()
                .eq(SplitGoods::getOrderId, id));
        if(list.size() < 1){
            throw  new NullInfoException(MessageConstant.SPLIT_GOODS_IS_NULL);
        }

        return list.stream().map(item -> {
            String trackingNumber = item.getTrackingNumber();

            SplitGoodsList splitGoodsList = new SplitGoodsList();
            splitGoodsList.setTrackingNumber(trackingNumber);
            // TODO 判断运单号是否为订单号，若为订单号，则此次并未拆分，封装返回订单信息

            List<OrderDetail> orderDetails = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getTrackingNumber, trackingNumber));
            List<LoadInformation> collect = orderDetails.stream().map(obj -> {
                LoadInformation loadInformation = new LoadInformation();
                BeanUtils.copyProperties(obj, loadInformation);
                return loadInformation;
            }).collect(Collectors.toList());

            splitGoodsList.setLoadInformation(collect);
            return splitGoodsList;
        }).collect(Collectors.toList());

    }
}
